<template>
  <div class="app-container">
    <!--查询-->
    <div class="my-bar">
      <el-button-group class="float-left">
        <el-button size="small" type="primary" icon="el-icon-edit" @click="onEdit()">新增</el-button>
        <el-button v-if="isOpenOrderNo" :loading="popData.loading" size="small" type="primary" icon="el-icon-edit" @click="saveOrderNo()">保存排序</el-button>
        <el-checkbox v-model="isOpenOrderNo" size="small" border>打开排序</el-checkbox>
      </el-button-group>
    </div>
    <!--树形Table default-expand-all -->
    <el-table v-loading="listData.loading" :data="listData.data" :tree-props="{children: 'childList'}" row-key="id" border>
      <el-table-column align="left" label="名称" width="180">
        <template slot-scope="scope">
          <!-- <i class="el-icon-plus"/> -->
          <i v-if="scope.row.icon" :class="scope.row.icon" />
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="router" label="路由" width="150" />
      <el-table-column align="center" prop="compt" label="vue文件" width="180" />
      <el-table-column align="center" prop="perms" label="权限" />
      <!-- <el-table-column align="center" prop="url" label="外链地址" width="150" /> -->
      <el-table-column align="center" prop="hide" label="显示状态" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.hide" size="mini">隐藏</el-tag>
          <el-tag v-else size="mini">显示</el-tag>
          <!-- <el-tag v-if="scope.row.status == 1" size="mini">正常</el-tag>
          <el-tag v-if="scope.row.status == 0" size="mini">禁用</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column :width="isOpenOrderNo ? 150: 230" prop="operation" fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button-group v-if="!isOpenOrderNo">
            <el-button v-if="scope.row.parentId == 0" size="mini" type="primary" @click="onAddChild(scope.row)">添加子菜单</el-button>
            <!-- <el-button v-else size="mini" type="primary" @click="$router.push({path: '/role/perm?id=' + scope.row.id})">权限</el-button> -->
            <el-button size="mini" type="primary" @click="onEdit(scope)">编辑</el-button>
            <el-button size="mini" type="danger" @click="func.cmStatus(_self, scope, 0, '删除')">删除</el-button>
          </el-button-group>
          <el-button-group v-else>
            <el-button size="mini" type="success" @click="onUp(scope.row)"><i class="el-icon-top" /></el-button>
            <el-button size="mini" type="primary" @click="onDown(scope.row)"><i class="el-icon-bottom" /></el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <!--新增和编辑-->
    <el-dialog :title="popData.title" :visible.sync="popData.show" size="small">
      <el-form ref="formData" :model="formData" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单名" required>
              <el-input v-model="formData.name" placeholder="请输入菜单名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由" required>
              <el-input v-model="formData.router" placeholder="请输入路由" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="vue文件" required>
              <el-input v-if="formData.parentId" v-model="formData.compt" placeholder="请输入文件夹/文件名" />
              <b v-else>Layout</b>
            </el-form-item>
          </el-col>
          <el-col v-if="!formData.parentId" :span="12">
            <el-form-item label="图标" required>
              <el-popover placement="bottom-start" width="560" trigger="click" @show="$refs['iconSelect'].reset()">
                <icon-select ref="iconSelect" @selected="selected" />
                <el-input slot="reference" v-model="formData.icon" placeholder="点击选择图标" readonly>
                  <!-- <svg-icon v-if="formData.icon" slot="prefix" :icon-class="formData.icon" class="el-input__icon" style="height: 32px;width: 16px;" />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon" /> -->
                  <i slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
              </el-popover>
              <!-- <el-select v-model="formData.icon" placeholder="请选择" filterable clearable>
                <el-option v-for="item in icons" :key="item" :label="item" :value="item">
                  <i :class="item" /> {{ item.replace('el-icon-', '') }}
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col v-if="formData.parentId" :span="12">
            <el-form-item v-if="formData.parentId" label="是否隐藏" required>
              <el-radio-group v-model="formData.hide">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="嵌入地址">
          <el-input v-model="formData.url" placeholder="请输入嵌入地址" />
        </el-form-item> -->
        <el-form-item label="权限列表">
          <!-- <el-input v-model="formData.perms" placeholder="请输入权限列表" /> -->
          <el-select
            v-model="permArr"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="权限列表"
            style="width:80%">
            <el-option value="list" label="list" />
            <el-option value="save" label="save" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="popData.show = false">取消</el-button>
        <el-button :loading="popData.loading" size="small" type="primary" @click="saveEvts">{{ popData.button }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/service'
import iconSelect from '@/views/compts/iconSelect'

export default {
  components: {
    iconSelect
  },
  data() {
    return {
      func: api,
      bean: 'role.menu',
      popData: { show: false, loading: false },
      getData: {
        pageNum: 1,
        pageSize: 300,
        showFlags: 'childList',
        params: {
          parentId: 0
        }
      },
      listData: {
        data: [],
        total: 0,
        loading: false
      },
      formData: {},
      editForm: {
        url: '',
        hide: false
      },
      loadings: [],
      icons: [],
      changes: [],
      isOpenOrderNo: false,
      permArr: []
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getListData()
      this.formData = JSON.parse(JSON.stringify(this.editForm))
    },
    getListData() {
      this.listData.loading = true
      api.getListPage(this.bean, this.getData).then(res => {
        this.listData.data = res.data
        this.listData.total = res.total
        this.listData.loading = false
        this.loadings = []
        for (const data of this.listData.data) {
          delete data.permList
          if (data.childList) {
            for (const child of data.childList) {
              delete child.permList
              // child.compt = child.compt.substring(0, child.compt.indexOf('/'))
            }
          }
        }
      })
    },
    // 选中图标
    selected(name) {
      console.log('selected', name)
      // this.formData.icon = name
      this.$set(this.formData, 'icon', name)
    },
    onUp(row) {
      api.onUp(this, this.listData.data, this.changes, row, 'orderNo')
    },
    onDown(row) {
      api.onDown(this, this.listData.data, this.changes, row, 'orderNo')
    },
    saveOrderNo() {
      const newList = []
      let orderNo = 0
      for (const data of this.listData.data) {
        newList.push({ id: data.id, orderNo: orderNo++ })
        if (data.childList) {
          for (const child of data.childList) {
            newList.push({ id: child.id, orderNo: orderNo++ })
          }
        }
      }
      api.saveChanges(this, newList, '保存排序')
    },
    onAddChild(row) {
      console.log('onAddChild', row)
      this.popData.show = true
      this.popData.loading = false
      this.popData.button = '新增子菜单'
      this.popData.title = '新增子菜单'
      this.formData = JSON.parse(JSON.stringify(this.editForm))
      this.formData.parentId = row.id
      // this.formData.sysId = row.sysId
      this.formData.icon = ''
      let orderNo = row.orderNo
      if (row.childList) {
        for (const child of row.childList) {
          orderNo = child.orderNo
        }
      }
      this.formData.orderNo = orderNo
    },
    onEdit(scope) {
      api.onEdit(this.$data, scope)
      if (!scope) {
        this.formData.parentId = 0
      }
      this.permArr = this.formData.perms ? this.formData.perms.split(',') : []
    },
    saveEvts() {
      this.$refs['formData'].validate(valid => {
        if (valid) {
          this.saveOne(this.formData, this.popData.title)
        } else {
          this.$message.error('请您仔细填写好信息！')
          return false
        }
      })
    },
    saveOne(data, title) {
      // 抛出错误修复
      delete data.permList
      delete data.childList
      const tmpData = JSON.parse(JSON.stringify(data))
      if (tmpData.parentId === 0) {
        // stmpData.parentId = '0'
        tmpData.compt = 'Layout'
        if (!tmpData.router.startsWith('/')) {
          tmpData.router = '/' + tmpData.router
        }
        tmpData.hide = false
      }
      if (!tmpData.compt) {
        if (!tmpData.url) {
          console.log('data', tmpData)
          this.$message.error('vue文件或者嵌入地址必须填写一个！')
          return
        }
        tmpData.compt = 'iframe/iframe'
      }
      tmpData.perms = this.permArr.join(',')
      this.$set(this.popData, 'loading', true)
      console.log('tmpData', tmpData)
      api.saveOne(this.bean, tmpData).then(res => {
        api.success(this, title).then(that => {
          that.popData.show = false
          that.popData.loading = false
          that.getListData()
        })
      }).catch(() => {
        this.loadings = []
        this.popData.loading = false
      })
    },
    // saveOrderNo() {
    //   this.$set(this.popData, 'loading', true)
    //   const newList = []
    //   let orderNo = 0
    //   for (const data of this.listData.data) {
    //     newList.push({ id: data.id, orderNo: orderNo++ })
    //     if (data.childList) {
    //       for (const child of data.childList) {
    //         newList.push({ id: child.id, orderNo: orderNo++ })
    //       }
    //     }
    //   }
    //   console.log('newList', newList)
    //   api.saveBatch(this.bean, newList).then(res => {
    //     api.success(this, '更新排序').then(that => {
    //       this.$set(this.popData, 'loading', false)
    //       that.getListData()
    //     })
    //   }).catch(() => {
    //     this.$set(this.popData, 'loading', false)
    //   })
    // }
  }
}
</script>
